<template>
  <div class="app-container">

    <!--名称精确查询-->
    <el-form :inline="true" :model="productListRequest" class="demo-product-inline">
      <el-form-item label="商品名称">
        <el-input v-model="productListRequest.productName" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品货号">
        <el-input v-model="productListRequest.productNumber" placeholder="商品货号"></el-input>
      </el-form-item>
      <el-form-item label="商品品牌">
        <el-select v-model="productListRequest.productBrandId" placeholder="请选择商品品牌">
          <el-option
            v-for="item in productBrandList"
            :label="item.brandName"
            :value="item.productBrandId"
            :key="item.productBrandId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="productListRequest.productStatus" placeholder="请选择审核状态">
          <el-option label="未审核" :value="0"></el-option>
          <el-option label="审核通过" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
        >新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--商品列表查询-->
    <el-table v-loading="loading" :data="productList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品编号" align="center" prop="productId"/>
      <el-table-column label="商品图片" align="center" prop="productPic">
        <template slot-scope="scope">
          <img :src="scope.row.productPic" width="100" height="100">
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName"/>
      <el-table-column label="商品货号" align="center" prop="productNumber"/>
      <el-table-column label="标签" align="center">
        <template slot-scope="scope">
          上架:
          <el-switch
            v-model="scope.row.isListing"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
            @change="updStatus(scope.row)">
          </el-switch>
          <br>
          新品:
          <el-switch
            v-model="scope.row.isNew"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
            @change="updStatus(scope.row)">
          </el-switch>
          <br>
          推荐:
          <el-switch
            v-model="scope.row.isRecommended"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"
            :inactive-value="1"
            @change="updStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="isSort"/>
      <el-table-column label="销量" align="center" prop="salesVolume"/>
      <el-table-column label="审批状态" align="center" prop="productStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.productStatus == 0" size="mini" type="danger">未审核</el-tag>
          <el-tag v-else-if="scope.row.productStatus == 1" size="mini" type="success">审核通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="productListRequest.pageNum"
        :page-sizes="[3, 5, 7, 20]"
        :page-size="productListRequest.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 添加或修改品牌对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>

      <el-steps :active="active" finish-status="success">
        <el-step title="填写商品信息"></el-step>
        <el-step title="填写商品促销"></el-step>
        <el-step title="填写商品属性"></el-step>
        <el-step title="选择商品关联"></el-step>
      </el-steps>
      <div style="width: 60%;margin-left: 130px">
        <!--      商品信息表单(1)-->
        <el-form :rules="rules" ref="product" :model="product" v-if="active == 0">
          <el-form-item label="商品分类" :label-width="formLabelWidth" prop="productTypeIdList">
            <el-cascader
              v-model="product.productTypeIdList"
              :options="productTypeList"
              @change="handleChange"
              :props="{'value':'productTypeId','label':'typeName','children':'list'}"></el-cascader>
          </el-form-item>
          <el-form-item label="商品名称" :label-width="formLabelWidth" prop="productName">
            <el-input v-model="product.productName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="副标题" :label-width="formLabelWidth" prop="productSubheading">
            <el-input v-model="product.productSubheading" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品品牌" :label-width="formLabelWidth" prop="productBrandId">
            <el-select v-model="product.productBrandId" placeholder="请选择商品品牌">
              <el-option
                v-for="item in productBrandList"
                :label="item.brandName"
                :value="item.productBrandId"
                :key="item.productBrandId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品介绍" :label-width="formLabelWidth" prop="productIntroduce">
            <el-input v-model="product.productIntroduce" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品货号" :label-width="formLabelWidth" prop="productNumber">
            <el-input v-model="product.productNumber" autocomplete="off" readonly></el-input>
          </el-form-item>
          <el-form-item label="商品售价" :label-width="formLabelWidth" prop="productPrice">
            <el-input v-model="product.productPrice" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="市场价" :label-width="formLabelWidth" prop="productMarketPrice">
            <el-input v-model="product.productMarketPrice" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品库存" :label-width="formLabelWidth" prop="productInventory">
            <el-input v-model="product.productInventory" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="计量单位" :label-width="formLabelWidth" prop="productUnit">
            <el-input v-model="product.productUnit" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" :label-width="formLabelWidth" prop="productWeight">
            <el-input v-model="product.productWeight" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="排序" :label-width="formLabelWidth">
            <el-input v-model="product.isSort" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
      </div>


      <div style="width: 70%;margin-left: 130px">
        <!--      商品信息表单(2)-->
        <el-form :rules="rules1" ref="product1" :model="product" v-if="active == 1">
          <el-form-item label="赠送积分" :label-width="formLabelWidth" prop="productPoints">
            <el-input v-model="product.productPoints" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="赠送成长值" :label-width="formLabelWidth" prop="productGrow">
            <el-input v-model="product.productGrow" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="积分购买限制" :label-width="formLabelWidth" prop="pointsBuyRestrict">
            <el-input v-model="product.pointsBuyRestrict" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="预告商品" :label-width="formLabelWidth" prop="productForetell">
            <el-switch v-model="product.productForetell"
                       active-color="#13ce66" inactive-color="#ff4949"
                       :active-value="0" :inactive-value="1"></el-switch>
          </el-form-item>
          <el-form-item label="商品上架" :label-width="formLabelWidth" prop="isListing">
            <el-switch v-model="product.isListing"
                       active-color="#13ce66" inactive-color="#ff4949"
                       :active-value="0" :inactive-value="1"></el-switch>
          </el-form-item>
          <el-form-item label="商品推荐" :label-width="formLabelWidth" prop="isNew">
            新品
            <el-switch v-model="product.isNew"
                       active-color="#13ce66" inactive-color="#ff4949"
                       :active-value="0" :inactive-value="1"></el-switch>
            推荐
            <el-switch v-model="product.isRecommended"
                       active-color="#13ce66" inactive-color="#ff4949"
                       :active-value="0" :inactive-value="1"></el-switch>
          </el-form-item>
          <el-form-item label="服务保证" :label-width="formLabelWidth" prop="serviceGuaranteeIds">
            <el-checkbox-group v-model="product.serviceGuaranteeIds">
              <el-checkbox
                v-for="item in serviceGuaranteeList"
                :key="item.serviceGuaranteeId"
                :label="item.serviceGuaranteeId">
                {{ item.serviceGuaranteeName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="详细页标题" :label-width="formLabelWidth" prop="detailsTitle">
            <el-input v-model="product.detailsTitle" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="详细页描述" :label-width="formLabelWidth" prop="detailsDescription">
            <el-input v-model="product.detailsDescription" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品备注" :label-width="formLabelWidth" prop="productRamark">
            <el-input v-model="product.productRamark" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品关键字" :label-width="formLabelWidth" prop="productKeyword">
            <el-input v-model="product.productKeyword" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="优惠方式" :label-width="formLabelWidth" prop="productKeyword">
            <el-radio-group v-model="product.preferentialMode">
              <el-radio-button :label="0">无优惠</el-radio-button>
              <el-radio-button :label="1">特惠促销</el-radio-button>
              <el-radio-button :label="2">会员价格</el-radio-button>
              <el-radio-button :label="3">阶梯价格</el-radio-button>
              <el-radio-button :label="4">满减价格</el-radio-button>
            </el-radio-group>
            <!--          特惠促销表单-->
            <el-form :model="product" v-if="product.preferentialMode === 1"
                     style="margin-top: 30px;margin-right: 60px">
              <el-form-item label="开始时间" :label-width="formLabelWidth">
                <el-date-picker
                  v-model="product.startTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择开始日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间" :label-width="formLabelWidth">
                <el-date-picker
                  v-model="product.endTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择结束日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="促销价格" :label-width="formLabelWidth" prop="promotionPrice">
                <el-input v-model="product.promotionPrice" autocomplete="off" placeholder="促销价格"></el-input>
              </el-form-item>
            </el-form>
            <!--          会员价格表单-->
            <el-table :data="product.memberPriceList" v-if="product.preferentialMode === 2">
              <el-table-column prop="memberLevelName" width="180">
                <template slot-scope="scope">
                  {{ scope.row.memberLevelName }}
                </template>
              </el-table-column>
              <el-table-column prop="memberPrice" label="价格" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.memberPrice" autocomplete="off"></el-input>
                </template>
              </el-table-column>
            </el-table>
            <!--          阶梯价格表格表单-->
            <el-table :data="product.ladderList" border style="width: 100%"
                      v-if="product.preferentialMode === 3">
              <el-table-column prop="productCount" label="数量" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.productCount" autocomplete="off"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="discount" label="折扣" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.discount" autocomplete="off"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="addLadderList()">添加</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" v-if="product.ladderList.length > 1"
                             @click="deleteLadderList(scope.index)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--          满减价格表格表单-->
            <el-table :data="product.fullReductionList" border style="width: 100%"
                      v-if="product.preferentialMode === 4">
              <el-table-column prop="fullPrice" label="满" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.fullPrice" autocomplete="off"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="reducePrice" label="立减" width="180">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.reducePrice" autocomplete="off"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="addFullReductionList()">添加
                  </el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" v-if="product.fullReductionList.length > 1"
                             @click="deleteFullReductionList(scope.index)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <!--      商品信息表单(3)-->
      <div style="width: 60%;margin-left: 130px">
        <el-form :rules="rules2" ref="product2" :model="product" v-if="active === 2">
          <el-form-item label="属性类型" :label-width="formLabelWidth" prop="productAttrId">
            <el-select v-model="product.productAttrId" placeholder="请选择属性类型" @change="findByProductAttrList">
              <el-option
                v-for="item in productAttrList"
                :label="item.productAttrName"
                :value="item.productAttrId"
                :key="item.productAttrId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品规格" :label-width="formLabelWidth" prop="productAttrValue">
            <el-card class="box-card">
              <div v-for="(stats,index) in statsAllList" :key="index">
                {{ stats.name + ":" }}
                <el-checkbox-group v-model="checkList[index]" @change="changeCheckList(index)">
                  <el-checkbox
                    v-for="itemCheck in getCheckList(stats.selectable)"
                    :label="itemCheck"
                    :key="itemCheck">
                    {{ itemCheck }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </el-card>
          </el-form-item>
          <!--商品规格列表-->
          <el-table v-loading="loading" :data="combinedList" style="margin: 0 auto; width:100%">
            <el-table-column
              v-for="(stats,index) in statsAllList"
              prop="salePrice"
              :label="stats.name"
              width="80">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.combined.split('-')[index] }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="salePrice" label="销售价格" width="80">
              <template slot-scope="scope">
                <el-input v-model="scope.row.salePrice" autocomplete="off"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="promotionalPrice" label="促销价格" width="80">
              <template slot-scope="scope">
                <el-input v-model="scope.row.promotionalPrice" autocomplete="off"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="productStack" label="商品库存" width="80">
              <template slot-scope="scope">
                <el-input v-model="scope.row.productStack" autocomplete="off"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="forewarningStack" label="库存预警值" width="80">
              <template slot-scope="scope">
                <el-input v-model="scope.row.forewarningStack" autocomplete="off"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="skuNumber" label="SKU编号" width="80">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuNumber" autocomplete="off"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <!--          //刷新按钮-->
          <el-button type="primary" @click="refresh()">刷新列表</el-button>
          <el-form-item label="商品相册" prop="brandLogo">
            <imageUpload v-model="product.productPic" :limit="1"></imageUpload>
          </el-form-item>
        </el-form>
      </div>
      <div style="width: 80%;margin-left: 70px">
        <!--      商品信息表单(4)-->
        <el-form :rules="rules3" ref="product3" :model="product" v-if="active === 3">
          <el-form-item label="关联专题" :label-width="formLabelWidth" prop="subjectIds">
            <el-transfer
              filterable
              :filter-method="filterMethod"
              filter-placeholder="请输入关联专题"
              v-model="product.subjectIds"
              :titles="['可选', '已选']"
              :data="subjectList">
            </el-transfer>
          </el-form-item>
          <el-form-item label="关联优选" :label-width="formLabelWidth" prop="preferenceIds">
            <el-transfer
              filterable
              :filter-method="filterMethodPreferenceName"
              filter-placeholder="请输入关联优选"
              v-model="product.preferenceIds"
              :titles="['可选', '已选']"
              :data="preferenceList">
            </el-transfer>
          </el-form-item>
        </el-form>
      </div>

      <el-button type="primary" @click="up()" v-if="active !== 0 ">上一步</el-button>
      <el-button type="primary" @click="next()" v-if="active !== 3">下一步</el-button>
      <el-button type="primary" @click="submitForm" v-if="active === 3">提交</el-button>
    </el-dialog>
  </div>
</template>

<script>


import {
  addProduct,
  deleteProduct, findByAttrIdStatsAll,
  findByFullReductionList,
  findByLadderList,
  findByMemberPriceList, findByPreferenceMidden,
  findByServiceGuaranteemidden,
  findBySubjectmidden,
  findProductList,
  findServiceGuaranteeAll,
  updateProduct,
  updateProductStatus
} from "../../api/product/product";
import {findProductBrandAll} from "../../api/product/productBrand/productBrand";
import {findLinkageList} from "../../api/product/productType/productType";
import {findProductAttrAll} from "../../api/product/productAttr/productAttr";
import {findSubjectListAll} from "../../api/marketing/subject/subject";
import {findPreferenceListAll} from "../../api/marketing/preference/preference";

export default {
  name: "Post",
  dicts: ['sys_normal_disable'],
  data() {

    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      //商品类型列表
      productAttrList: [],
      //商品分类级联列表
      productTypeList: [],
      //商品分类级联列表
      productBrandList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品类别表格数据
      productList: [],
      // 推荐优选数据
      preferenceList: [],
      // 推荐专题数据
      subjectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      productListRequest: {
        productName: '',
        productNumber: null,
        productBrandId: null,
        productStatus: null,
        pageNum: 1,
        pageSize: 5
      },
      formLabelWidth: '120px',
      // 表单参数
      product: {},
      //步骤一表单参数校验
      rules: {
        productName: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        productTypeIdList: [
          {type: 'array', required: true, message: '请选择商品分类', trigger: 'change'}
        ],
        productSubheading: [
          {required: true, message: '请输入副标题', trigger: 'blur'}
        ],
        productBrandId: [
          {required: true, message: '请选择商品品牌', trigger: 'change'}
        ],
        productIntroduce: [
          {required: true, message: '请输入商品介绍', trigger: 'blur'}
        ],
        productUnit: [
          {required: true, message: '请输入计量单位', trigger: 'blur'}
        ]
      },
      //步骤二表单参数校验
      rules1: {
        // serviceGuaranteeIds: [
        //   {type: 'array', required: true, message: '请至少选择一个服务保证', trigger: 'blur'}
        // ],
        productTypeId: [
          {required: true, message: '请选择商品分类', trigger: 'change'}
        ],
        productSubheading: [
          {required: true, message: '请输入副标题', trigger: 'blur'}
        ],
        productBrandId: [
          {required: true, message: '请选择商品品牌', trigger: 'change'}
        ],
        productIntroduce: [
          {required: true, message: '请输入商品介绍', trigger: 'blur'}
        ],
        productPrice: [
          {required: true, message: '请输入商品售价', trigger: 'blur'}
        ],
        productMarketPrice: [
          {required: true, message: '请输入市场价', trigger: 'blur'}
        ],
        productInventory: [
          {required: true, message: '请输入商品库存', trigger: 'blur'}
        ],
        productUnit: [
          {required: true, message: '请输入计量单位', trigger: 'blur'}
        ],
        productWeight: [
          {required: true, message: '请输入商品重量', trigger: 'blur'}
        ]
      },
      //步骤三表单参数校验
      rules2: {
        productAttrId: [
          {required: true, message: '请选择属性类型', trigger: 'blur'}
        ]
      },
      //步骤四表单参数校验
      rules3: {
        // subjectIds: [
        //   {type: 'array', required: true, message: '至少选择一个专题', trigger: 'blur'}
        // ]
      },
      active: 0,
      //服务保证复选框
      serviceGuaranteeList: [],
      //查询指定类型的商品属性
      statsAllList: [
        {
          statsIds: []
        }
      ],
      //查询指定类型的商品参数
      parameterAllList: [],
      //商品属性ids
      statsIds: [
        {
          res: []
        }
      ],
      checkList: {},
      combinedList: []
    };
  },
  created() {
    this.getList();
    this.getBrandList();
    this.getTypeLinkageList();
    this.getAttrList();
    this.getSubjectList();
    this.getServiceGuaranteeList();
    this.getPreferenceList();

  },
  methods: {
    refresh() {
      this.combinedList = []
      this.combineLists();
    },
    combineLists() {
      // 确保 checkLists 已经被初始化并且是一个对象
      if (!this.checkList || typeof this.checkList !== 'object') {
        console.error('checkLists is not initialized properly.');
        return [];
      }
      const keys = Object.keys(this.checkList);
      // 确保至少有两个列表
      if (keys.length < 2) {
        return [];
      }
      // 选择前两个列表进行组合
      const list1 = this.checkList[keys[0]] || [];
      const list2 = this.checkList[keys[1]] || [];
      // 使用 map 和 concat 来组合两个列表
      const combinedList = list1.flatMap(color =>
        list2.map(size => ({combined: `${color}-${size}`}))
      );
      // 返回组合后的列表
      console.log('Combined List:', combinedList);
      this.combinedList = combinedList;
      return this.combinedList;
    },
    initializeCheckLists(data) {
      // 确保为 statsAllList 中的每一项都初始化一个空数组
      data.forEach((_, index) => {
        this.$set(this.checkList, index, []);
      });
    },
    changeCheckList(index) {

    },
    getCheckList(selectable) {
      console.log(selectable)
      if (selectable === undefined || selectable === null || selectable === '') {
        return [];
      }
      let split = selectable.split(',');
      return split;
    },
    findByProductAttrList() {
      this.checkList = {}
      this.combinedList = []
      if (this.product.productAttrId) {
        findByAttrIdStatsAll(this.product.productAttrId, 0).then(res => {
          this.statsAllList = res.data
          this.initializeCheckLists(res.data);
        })
        // findByAttrIdStatsAll(this.product.productAttrId, 1).then(res => {
        //   this.parameterAllList = res.data
        //   console.log(res.data);
        //   console.log("赋值后的参数集合" + JSON.stringify(this.parameterAllList));
        // })
      }
    },
    getServiceGuaranteeList() {
      findServiceGuaranteeAll().then(res => {
        this.serviceGuaranteeList = res.data
      })
    },
    filterMethod(query, item) {
      //subjectName
      return item.label.toLowerCase().includes(query.toLowerCase());
    },
    filterMethodPreferenceName(query, item) {
      //preferenceName
      return item.label.toLowerCase().includes(query.toLowerCase());
    },
    getSubjectList() {
      findSubjectListAll().then(res => {
        this.subjectList = res.data.map(item => ({
          label: item.subjectName,
          key: item.subjectId
        }))
      })
    },
    getPreferenceList() {
      findPreferenceListAll().then(res => {
        this.preferenceList = res.data.map(item => ({
          label: item.preferenceName,
          key: item.preferenceId
        }))
      })
    },
    /** 删除满减价格*/
    deleteFullReductionList(index) {
      this.product.fullReductionList.splice(index, 1)
    },
    /** 添加满减价格*/
    addFullReductionList() {
      this.product.fullReductionList.push(
        {
          productFullReductionId: 0,
          productId: 0,
          fullPrice: 0,
          reducePrice: 0
        }
      )
    },
    /** 删除阶梯价格*/
    deleteLadderList(index) {
      this.product.ladderList.splice(index, 1)
    },
    /** 添加阶梯价格*/
    addLadderList() {
      this.product.ladderList.push(
        {
          productLadderId: 0,
          productId: 0,
          productCount: 0,
          discount: 0,
          discountPrices: 0
        }
      )
    },
    getAttrList() {
      findProductAttrAll().then(res => {
        this.productAttrList = res.data
      })
    },
    getTypeLinkageList() {
      findLinkageList().then(res => {
        this.productTypeList = res.data
      })
    },
    getBrandList() {
      findProductBrandAll().then(res => {
        this.productBrandList = res.data
      })
    },
    handleChange(value) {
      console.log(value);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.productListRequest.pageSize = val;
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.productListRequest.pageNum = val;
      this.getList()
    },
    up() {
      this.active--;
    },
    next() {
      var formName = ''
      if (this.active === 0) {
        formName = 'product';
      }
      if (this.active === 1) {
        formName = 'product1';
      }
      if (this.active === 2) {
        formName = 'product2';
      }
      if (this.active === 3) {
        formName = 'product3';
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.product);
          console.log('验证' + formName + '成功');
          if (this.active++ > 3) this.active = 0;
        } else {
          return false;
        }
      });
    },
    /** 多选框选中数据 */
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.id)
    //   this.single = selection.length != 1
    //   this.multiple = !selection.length
    // },
    /** 提交表单 查询品牌名称*/
    onSubmit() {
      this.getList();
    },
    /** 改变上架状态 */
    /** 改变新品状态 */
    /** 改变推荐状态 */
    updStatus(row) {
      if (row.productId != undefined) {
        updateProductStatus(row).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.getList();
        });
      }
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      findProductList(this.productListRequest).then(response => {
        this.productList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.product = {
        productId: undefined,
        productPic: '',
        productName: '',
        productNumber: new Date().getTime(),
        isListing: undefined,
        isNew: undefined,
        isRecommended: undefined,
        isSort: 0,
        salesVolume: 0,
        productStatus: 0,
        isDelete: 0,
        productSubheading: '',
        productIntroduce: '',
        productPrice: 0,
        productMarketPrice: 0,
        productInventory: 0,
        productUnit: '',
        productWeight: 0,
        productTypeId: null,
        productBrandId: null,
        productPoints: 0,
        productGrow: 0,
        pointsBuyRestrict: 0,
        productForetell: undefined,
        serviceGuaranteeIds: [],
        detailsTitle: undefined,
        detailsDescription: undefined,
        productKeyword: undefined,
        productRamark: undefined,
        preferentialMode: 0,
        startTime: undefined,
        endTime: undefined,
        promotionPrice: undefined,
        productAttrId: undefined,
        productTypeIds: '',
        //关联优选
        preferenceIds: [],
        //关联专题
        subjectIds: [],
        //商品分类级联
        productTypeIdList: [],
        //阶梯价格列表
        ladderList: [
          {
            productLadderId: 0,
            productId: 0,
            productCount: 0,
            discount: 0,
            discountPrices: 0
          }
        ],
        //会员价格列表
        memberPriceList: [
          {
            memberPriceId: 0,
            productId: 0,
            memberPrice: 0,
            //黄金会员
            memberLevelId: 1,
            memberLevelName: '黄金会员'
          },
          {
            memberPriceId: 0,
            productId: 0,
            memberPrice: 0,
            //铂金会员
            memberLevelId: 2,
            memberLevelName: '铂金会员'
          },
          {
            memberPriceId: 0,
            productId: 0,
            memberPrice: 0,
            //钻石会员
            memberLevelId: 3,
            memberLevelName: '钻石会员'
          }
        ],
        //满减价格列表
        fullReductionList: [
          {
            productFullReductionId: 0,
            productId: 0,
            fullPrice: 0,
            reducePrice: 0
          }
        ],
      };
      this.resetForm("form");
    },
    /**计算阶梯折后价格*/
    updateDiscountPrices() {
      this.product.ladderList.forEach(item => {
        item.discountPrices = item.discount * this.product.productMarketPrice
      })
      console.log(this.product.ladderList)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.productListRequest.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.product = row


      //productTypeIds 处理商品分类的数组
      let productTypeIdList = this.product.productTypeIds.split(',')
      this.product.productTypeIdList = productTypeIdList.map((item) => {
        return item = parseInt(item, 10)
      })

      this.open = true;
      this.product.productTypeId = this.product.productTypeIdList[0]
      this.product.productTypeIdList = this.product.productTypeIdList.reverse()
      findBySubjectmidden(this.product.productId).then(res => {
        this.product.subjectIds = res.data
      })
      findByServiceGuaranteemidden(this.product.productId).then(res => {
        this.product.serviceGuaranteeIds = res.data
      })
      findByPreferenceMidden(this.product.productId).then(res => {
        this.product.preferenceIds = res.data
      })
      findByLadderList(this.product.productId).then(res => {
        if (res.data.length > 0) {
          this.product.ladderList = res.data
        } else {
          this.product.ladderList = [{
            productCount: 0,
            discount: 0
          }]
        }
      })
      findByMemberPriceList(this.product.productId).then(res => {
        if (res.data.length > 0) {
          this.product.memberPriceList = res.data
        } else {
          this.product.memberPriceList = [
            {
              memberPrice: 0,
              //黄金会员
              memberLevelId: 1,
              memberLevelName: '黄金会员'
            },
            {
              memberPrice: 0,
              //铂金会员
              memberLevelId: 2,
              memberLevelName: '铂金会员'
            },
            {
              memberPrice: 0,
              //钻石会员
              memberLevelId: 3,
              memberLevelName: '钻石会员'
            }
          ]
        }
      })
      findByFullReductionList(this.product.productId).then(res => {
        if (res.data.length > 0) {
          this.product.fullReductionList = res.data
        } else {
          this.product.fullReductionList = [
            {
              fullPrice: 0,
              reducePrice: 0
            }
          ]
        }
      })
      this.findByProductAttrList()
      // console.log(this.product);
      this.title = "修改商品";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.updateDiscountPrices();
      this.product.productTypeId = this.product.productTypeIdList[this.product.productTypeIdList.length - 1]
      console.log(this.product);
      if (this.product.productId != undefined) {
        updateProduct(this.product).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
          this.reset()
          this.active = 0
        });
      } else {
        addProduct(this.product).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
          this.reset()
          this.active = 0
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.productId || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + id + '"的数据项？').then(function () {
        return deleteProduct(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.productListRequest
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<!--<style>-->
<!--.text {-->
<!--  font-size: 14px;-->
<!--}-->

<!--.item {-->
<!--  padding: 18px 0;-->
<!--}-->

<!--.box-card {-->
<!--  width: 480px;-->
<!--}-->
<!--</style>-->
